﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HREDU.Hoang_Tuan.Classes;
using HREDU.Hoang_Tuan;


namespace HREDU
{
    public partial class frmDONVI : Form
    {
        private ListViewColumnSorter lvwColumnSorter;
        public Form fCallForm;
        public string nhomCha = "";
        const byte CtrlMask = 8;
        private enumNHOM nhom;
        private string name  ="";

        //Dau vao ten cac column se xu ly trong treeview va listview
        private string nhomColumnName = CDONVICollection.nhomColumnName;
        private string tenColumnName = CDONVICollection.tenColumnName;
        private string cuoiColumnName = CDONVICollection.cuoiColumnName;

        #region "New"
        public frmDONVI()
        {
            // This call is required by the Windows Form Designer.
            InitializeComponent();
            // Create an instance of a ListView column sorter and assign it
            // to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvControl.ListViewItemSorter = lvwColumnSorter;
        }

        public frmDONVI(enumNHOM eNhom)
        {

            // This call is required by the Windows Form Designer.
            InitializeComponent();

            // Add any initialization after the InitializeComponent() call.
            nhom = eNhom;
            if (nhom == enumNHOM.DONVI)
                name = "Đơn vị";
            else
                name = "Chức vụ";
            this.Text = "Danh mục " + name;

            //Hide button chon khi mo truc tiep Danh muc
            btnChon.Visible = false;

            // Create an instance of a ListView column sorter and assign it
            // to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvControl.ListViewItemSorter = lvwColumnSorter;
            
        }

        public frmDONVI(Form frmCall, enumNHOM eNhom)
        {
            // This call is required by the Windows Form Designer.
            InitializeComponent();

            // Add any initialization after the InitializeComponent() call.
            fCallForm = frmCall;
            nhom = eNhom;
            // Create an instance of a ListView column sorter and assign it
            // to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvControl.ListViewItemSorter = lvwColumnSorter;
        }
        #endregion


        private void frmDONVI_Load(object sender, EventArgs e)
        {
            InitTreeView();
            InitListView();
            InitContextMenu();
        }

        #region "tvControl"

        #region "tvControl Functions"

        //Add node dau tien cua treeview
        public void FormatFirstNode(ref TreeNode node)
        {
            node.ForeColor = Color.Blue;
            //node.NodeFont = new Font(this.Font.Name, this.Font.Size + 1.0F, FontStyle.Bold);
            //node.NodeFont = new Font(this.Font, FontStyle.Bold);
            node.ImageIndex = 0;
            node.SelectedImageIndex = 0;
        }

        public void FormatChildNode(ref TreeNode node)
        {
            node.ForeColor = Color.DarkRed;
            //node.NodeFont = new Font(this.Font, FontStyle.Bold);
            node.ImageIndex = 0;
            node.SelectedImageIndex = 0;
        }

        public void InitTreeView()
        {
            tvControl.ContextMenuStrip = ContextMenuStrip2;
            //Lay danh muc tree view dau tien
            string strSQL;

            //Neu la nhom DON VI
            if (nhom == enumNHOM.DONVI)
                strSQL = "select * from DONVI where left(nhom,3) = '002' and len(nhom) = (select min(len(nhom)) from DONVI)"; //
            else //Neu la nhom CHUC VU
                strSQL = "select * from DONVI where left(nhom,3) = '001' and len(nhom) = (select min(len(nhom)) from DONVI)"; //len(nhom) = (select min(len(nhom)) from DONVI)

            DataSet ds = MITI.BaseDB.Instance.ExecSql_DataSet(strSQL);
            
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //Add Node in Treeview
                TreeNode node = tvControl.Nodes.Add(dr[nhomColumnName].ToString(), dr[tenColumnName].ToString());

                //Kiem tra node co phai la node dau cua treeview khong
                //Neu bang thi cho mau xanh, nguoc lai mau do
                if (((bool)dr[cuoiColumnName] == false))
                {
                    //Tra ve node theo format dinh san
                    FormatFirstNode(ref node);
                }
                else
                {
                    //Tra ve node theo format dinh san
                    FormatChildNode(ref node);
                }
            }
            tvControl.Focus();
            tvControl.SelectedNode = tvControl.Nodes[0];
        }

        public void LoadTreeView(string nhomCha)
        {
            tvControl.ImageList = ImageList1;

            //Tim node co theo ten va tra ve kq
            TreeNode[] nodes = tvControl.Nodes.Find(nhomCha, true);
            TreeNode node;

            //Neu khong co node nao tim thay
            if (nodes.Length == 0)
            {
                return; 
            }

            //Lay node dau tien trong cac node tim thay
            node = nodes[0];

            //Neu node lay co cac node con thi xoa di
            if (node.Nodes.Count > 0)
            {
                node.Nodes.Clear();
            }

            //Lay cac node con theo node can tim
            DataTable db = CDONVICollection.LayCoQuanTheoNhomCha_DataTable(nhomCha, 0);
            //Neu co node can tim co cac node con
            if (db.Rows.Count > 0)
            {
                //Tra ve node theo format dinh san
                if(node.Parent != null)
                    FormatChildNode(ref node);
                else
                    FormatFirstNode(ref node);
                
                foreach (DataRow dr in db.Rows)
                {
                    TreeNode childNode = node.Nodes.Add(dr[nhomColumnName].ToString(), dr[tenColumnName].ToString());
                    if (((bool)dr[cuoiColumnName] == false))
                    {
                        FormatChildNode(ref childNode);
                    }
                }
            }
        }

        public void HienThiGiaTriTimKiem(string nhomTimKiem)
        {
            TreeNode[] nodes = tvControl.Nodes.Find(nhomTimKiem, true);
            if (nodes.Length > 0)
            {
                tvControl.SelectedNode = nodes[0].Parent;
            }
            else
            {
                int maxlen = nhomTimKiem.Length;
                int len = 3;
                while (len < maxlen)
                {
                    LoadTreeView(nhomTimKiem.Substring(0, len));
                    len += 3;
                }
                //Neu nhomTimKiem co gia tri cuoi = False (tuc la hien thi tren TreeView) thi tim kiem tren TreeView
                //Nguoc lai se load Node Parent cua nhomTimKiem de tim kiem tren ListView
                if (CDONVICollection.LayGiaTriCuoiTheoNhom(nhomTimKiem) == false)
                {
                    nodes = tvControl.Nodes.Find(nhomTimKiem, true);
                    if (nodes.Length > 0)
                    {
                        tvControl.SelectedNode = nodes[0].Parent;
                    }
                }
                else
                {
                    nodes = tvControl.Nodes.Find(nhomTimKiem.Substring(0, nhomTimKiem.Length - 3), true);
                    if (nodes.Length > 0)
                    {
                        tvControl.SelectedNode = nodes[0];
                    }
                }
            }
            ListViewItem[] items = lvControl.Items.Find(nhomTimKiem, true);
            if (items.Length > 0)
            {
                items[0].Selected = true;
            }
        }
        #endregion

        private void tvControl_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            string nhomCha = tvControl.SelectedNode.Name;
            if (tvControl.SelectedNode.GetNodeCount(false) == 0)
            {
                LoadTreeView(nhomCha);
            }
            LoadListView(nhomCha);
        }

        private void tvControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", false))
            {
                ListViewItem srcItem = (ListViewItem)e.Data.GetData("System.Windows.Forms.ListViewItem");
                Point pt;
                TreeNode destNode;
                pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                //SelectedNode chinh la parent node cua srcItem
                //nen kiem tra voi destNode co trung nhau ko
                if (object.ReferenceEquals(tvControl.SelectedNode, destNode))
                {
                    MessageBox.Show("Nơi chuyển đi và đến không được trùng nhau");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcItem.Name).Rows[0];
                objDest = CDONVICollection.LayCoQuanTheoNhom_DataTable(destNode.Name).Rows[0];
                if (CDONVICollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDONVICollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if ((MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes))
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    objSrc[nhomColumnName] = CDONVICollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat lai gia tri cuoi node dang chon o TreeView
                    //sau khi di chuyen Item o LisView
                    if (!CDONVICollection.IsExistsChildNodes(tvControl.SelectedNode.Name, false))
                    {
                        DataTable db = CDONVICollection.LayCoQuanTheoNhom_DataTable(tvControl.SelectedNode.Name);
                        db.Rows[0][cuoiColumnName] = true;
                        CDONVICollection.Update(db.Rows[0]);
                    }
                    LoadTreeView(tvControl.SelectedNode.Name);

                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDONVICollection.Update(objDest);
                    LoadTreeView(objDest[nhomColumnName].ToString());

                    //Refresh TreeView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                TreeNode srcNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                if (object.ReferenceEquals(srcNode.Parent, destNode))
                {
                    MessageBox.Show("Nơi chuyển đi và đến không được trùng nhau");
                    return; // TODO: might not be correct. Was : Exit Sub
                }
                DataRow objSrc;
                DataRow objDest;
                objSrc = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcNode.Name).Rows[0];
                objDest = CDONVICollection.LayCoQuanTheoNhom_DataTable(destNode.Name).Rows[0];
                if (CDONVICollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDONVICollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if (MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    objSrc[nhomColumnName] = CDONVICollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refesh TreeView
                    //Cap nhat lai gia tri cuoi neu ko co childNode
                    if (!CDONVICollection.IsExistsChildNodes(srcNode.Parent.Name, false))
                    {
                        DataTable db = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcNode.Parent.Name);
                        db.Rows[0][cuoiColumnName] = true;
                        CDONVICollection.Update(db.Rows[0]);
                    }
                    LoadTreeView(srcNode.Parent.Name);
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDONVICollection.Update(objDest);
                    LoadTreeView(objDest[nhomColumnName].ToString());
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
        }

        private void tvControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem") | e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                if ((e.KeyState & CtrlMask) == CtrlMask)
                {
                    e.Effect = DragDropEffects.Copy;
                }
                else
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        public void KiemTraDragDrop(ref System.Windows.Forms.DragEventArgs e, string destKey, string srcKey)
        {
            //Kiem tra trang thai move hay copy (CtrlMask = 8 (1000) , e.KeyState = 1 (0001) hoac 9 (1001))
            if ((e.KeyState & CtrlMask) == CtrlMask)
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.Move;
            }

            //Kiem tra xem noi di va noi den co trung lap khong
            //1. Noi di trung voi noi den
            if (destKey == srcKey)
            {
                e.Effect = DragDropEffects.None;
            }
            //2. Noi den chua noi di (==> des length = src length + 3)
            else if (destKey.Length < srcKey.Length)
            {
                if (srcKey.Substring(0, srcKey.Length - 3) == destKey)
                    e.Effect = DragDropEffects.None;
            }
        }

        private void tvControl_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem"))
            {
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                ListViewItem srcItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (destNode != null)
                {
                    KiemTraDragDrop(ref e, destNode.Name, srcItem.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                TreeNode srcNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
                if (destNode != null)
                {
                    KiemTraDragDrop(ref e, destNode.Name, srcNode.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void tvControl_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move | DragDropEffects.Copy);
            }
        }

        private void tvControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                ListViewItem item = lvControl.GetItemAt(ClickPoint.X, ClickPoint.Y);
                {
                    if (item == null)
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = false;
                    }
                    else
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = true;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = true;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = true;
                    }

                    // Convert from Tree coordinates to Screen coordinates
                    Point ScreenPoint = lvControl.PointToScreen(ClickPoint);
                    // Convert from Screen coordinates to Formc coordinates
                    Point FormPoint = this.PointToClient(ScreenPoint);
                    //Show context menu
                    ContextMenuStrip1.Show(this, FormPoint);
                }
            }
        }
        #endregion

        #region "lvControl"

        #region "lvControl Functions"
        public void InitListView()
        {
            lvControl.ContextMenuStrip = ContextMenuStrip1;
            lvControl.SmallImageList = ImageList1;
            lvControl.Columns.Add("Tên " + name, lvControl.Width - 22, HorizontalAlignment.Left);
            lvControl.Columns.Add("Cuoi", 0, HorizontalAlignment.Center);
        }

        public void LoadListView(string nhomCha)
        {
            lvControl.Items.Clear();
            DataTable db = CDONVICollection.LayCoQuanTheoNhomCha_DataTable(nhomCha);
            ListViewItem item;
            foreach (DataRow dr in db.Rows)
            {
                item = new ListViewItem(dr[CDONVICollection.tenColumnName].ToString());
                if ((bool)dr[CDONVICollection.cuoiColumnName] == false)
                {
                    item.ImageIndex = 0;
                }
                else
                {
                    item.ImageIndex = 1;
                }
                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                subItem.Name = CDONVICollection.cuoiColumnName;
                //key of SubItem
                subItem.Text = dr[CDONVICollection.cuoiColumnName].ToString();
                item.SubItems.Add(subItem);
                item.Name = dr[CDONVICollection.nhomColumnName].ToString();
                lvControl.Items.Add(item);
            }
            //Count
            int folder = 0;
            int file = 0;
            CDONVICollection.CountChildNodes(nhomCha, ref folder, ref file);
            CountToolStripStatusLabel.Text = folder.ToString() + " Nhóm, " + file.ToString() + " " + name;
        }
        #endregion

        private void lvControl_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e)
        {
            // Determine if label is changed by checking to see if it is equal to Nothing.
            if (e.Label == null)
            {
                return;
            }
            if (lvControl.SelectedItems.Count > 0)
            {
                string nhomCha = "";
                nhomCha = tvControl.SelectedNode.Name;
                int cuoi = (lvControl.SelectedItems[0].SubItems[CDONVICollection.cuoiColumnName].Text == "False" ? 0 : 1);
                if (CDONVICollection.IsExists(nhomCha, e.Label, cuoi))
                {
                    MessageBox.Show("Tên '" + e.Label + "' này đã có.");
                    e.CancelEdit = true;
                    lvControl.SelectedItems[0].BeginEdit();
                    return; // TODO: might not be correct. Was : Exit Sub
                }
                if (e.Label != null)
                {
                    CDONVI clsLoaiVT = CDONVICollection.LayCoQuanTheoNhom(lvControl.SelectedItems[0].Name);
                    clsLoaiVT.TEN_DONVI = e.Label;
                    CDONVICollection.Update(clsLoaiVT);
                    lvControl.LabelEdit = false;
                }
                LoadTreeView(nhomCha);
            }
        }

        private void lvControl_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            // Determine if the clicked column is already the column that is
            // being sorted.
            if ((e.Column == lvwColumnSorter.SortColumn))
            {
                // Reverse the current sort direction for this column.
                if ((lvwColumnSorter.Order == SortOrder.Ascending))
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.lvControl.Sort();
        }

        private void lvControl_DoubleClick(object sender, System.EventArgs e)
        {
            if (CDONVICollection.LayCoQuanTheoNhom(lvControl.SelectedItems[0].Name).CUOI == false)
            {
                foreach (TreeNode node in tvControl.SelectedNode.Nodes)
                {
                    if (node.Name == lvControl.SelectedItems[0].Name)
                    {
                        tvControl.SelectedNode = node;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
                tvControl.SelectedNode.Expand();
            }
            //Neu la cuoi roi van cho them chi tiet cho cuoi
            //else
            //{
            //    LoadListView(lvControl.SelectedItems[0].Name);
            //}
        }

        private void lvControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                ListViewItem item = lvControl.GetItemAt(ClickPoint.X, ClickPoint.Y);
                {
                    if (item == null)
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = false;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ChọnĐơnVịToolStripMenuItem"].Visible = false;
                    }
                    else
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = true;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = true;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = true;
                        if (fCallForm != null)
                            ContextMenuStrip1.Items["ChọnĐơnVịToolStripMenuItem"].Visible = true;
                    }

                    // Convert from Tree coordinates to Screen coordinates
                    Point ScreenPoint = lvControl.PointToScreen(ClickPoint);
                    // Convert from Screen coordinates to Formc coordinates
                    Point FormPoint = this.PointToClient(ScreenPoint);
                    //Show context menu
                    ContextMenuStrip1.Show(this, FormPoint);
                }
            }
        }

        #region "ListView Drag Drop"
        private void lvControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem") | e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                if ((e.KeyState & CtrlMask) == CtrlMask)
                {
                    e.Effect = DragDropEffects.Copy;
                }
                else
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void lvControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", false))
            {
                ListViewItem srcItem = (ListViewItem)e.Data.GetData("System.Windows.Forms.ListViewItem");
                Point pt;
                ListViewItem destItem;
                pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcItem.Name).Rows[0];
                objDest = CDONVICollection.LayCoQuanTheoNhom_DataTable(destItem.Name).Rows[0];
                //Kiểm tra xem nơi chuyển đến có tồn tại objSrc chưa
                if (CDONVICollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDONVICollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if ((MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes))
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    CDONVICollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDONVICollection.Update(objDest);
                    LoadTreeView(tvControl.SelectedNode.Name);
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                TreeNode srcNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                Point pt;
                ListViewItem destItem;
                pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                if (destItem == null)
                {
                    // Trường hợp chọn chuyển vào ListView mà ko chọn Item cụ thể nào
                    DataRow dr = CDONVICollection.LayCoQuanTheoNhom_DataTable(tvControl.SelectedNode.Name).Rows[0];
                    //Lay tam mot item roi gan gia tri moi vao
                    destItem = new ListViewItem(dr[CDONVICollection.tenColumnName].ToString());
                    destItem.SubItems.Add("");
                    destItem.SubItems.Add("");
                    destItem.SubItems.Add("");
                    destItem.Name = dr[CDONVICollection.tenColumnName].ToString();
                    //Nếu chuyển vào ListView mà không chọn Item cụ thể thì có 2 trường hợp:
                    //**TH1: srcNode chuyển vào ngay trong thư mục của chính nó
                    //**Th2: srcNode có thư mục cha trùng với thư mục cha của nơi chuyển đến
                    if ((object.ReferenceEquals(srcNode, tvControl.SelectedNode)) || (object.ReferenceEquals(srcNode.Parent, tvControl.SelectedNode)))
                    {
                        MessageBox.Show("Nơi chuyển đi và nơi chuyển đến không được trùng nhau");
                        return; // TODO: might not be correct. Was : Exit Sub
                    }
                }
                else
                {
                    if (object.ReferenceEquals(srcNode.Parent, tvControl.SelectedNode.Nodes[destItem.Name]))
                    {
                        MessageBox.Show("Nơi chuyển đi và nơi chuyển đến không được trùng nhau");
                        return; // TODO: might not be correct. Was : Exit Sub
                    }
                }

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcNode.Name).Rows[0];
                objDest = CDONVICollection.LayCoQuanTheoNhom_DataTable(destItem.Name).Rows[0];
                if (CDONVICollection.IsExists(objDest[CDONVICollection.nhomColumnName].ToString(), objSrc[CDONVICollection.tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[CDONVICollection.tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[CDONVICollection.tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDONVICollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if ((MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes))
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    CDONVICollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat lai gia tri cuoi neu ko co childNode
                    if (!CDONVICollection.IsExistsChildNodes(srcNode.Parent.Name, false))
                    {
                        DataTable db = CDONVICollection.LayCoQuanTheoNhom_DataTable(srcNode.Parent.Name);
                        db.Rows[0][CDONVICollection.cuoiColumnName] = true;
                        CDONVICollection.Update(db.Rows[0]);
                    }
                    LoadTreeView(srcNode.Parent.Name);
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[CDONVICollection.cuoiColumnName] = false;
                    CDONVICollection.Update(objDest);
                    LoadTreeView(objDest[CDONVICollection.nhomColumnName].ToString());
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
        }

        private void lvControl_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem"))
            {
                ListViewItem destItem;
                Point pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                ListViewItem srcItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (destItem != null)
                {
                    KiemTraDragDrop(ref e, destItem.Name, srcItem.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                ListViewItem destItem;
                Point pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                TreeNode srcNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
                if (destItem != null)
                {
                    KiemTraDragDrop(ref e, destItem.Name, srcNode.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void lvControl_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move | DragDropEffects.Copy);
            }
        }

        #endregion

        #endregion

        #region "Context Menu"
        public void InitContextMenu()
        {
            //Đổi lại tên cho phù hợp với danh mục cần gọi
            ContextMenuStrip1.Items["thêmĐơnVịToolStripMenuItem"].Text = "Thêm " + name;
            contextMenuStrip3.Items["thêmĐơnVịToolStripMenuItem1"].Text = "Thêm " + name;
        }

        public string TaoTenNhomMoi()
        {
            string strTenBanDau = "";
            strTenBanDau = "Nhóm mới";
            int count = 0;
            bool isStop = false;
            string strTenMoi = strTenBanDau;
            while (!isStop)
            {
                int i = 0;
                for (i = 0; i <= tvControl.SelectedNode.Nodes.Count - 1; i++)
                {
                    TreeNode node = tvControl.SelectedNode.Nodes[i];
                    if (strTenMoi == node.Text)
                    {
                        count += 1;
                        strTenMoi = strTenBanDau + " (" + count + ")";
                        break; 
                    }
                }
                if (i == tvControl.SelectedNode.Nodes.Count)
                {
                    isStop = true;
                }
            }
            return strTenMoi;
        }

        public string TaoTenCoQuanMoi()
        {
            string strTenBanDau = "";
            strTenBanDau = "Tên " + name + " mới";
            int count = 0;
            bool isStop = false;
            string strTenMoi = strTenBanDau;
            while (!isStop)
            {
                int i = 0;
                for (i = 0; i <= lvControl.Items.Count - 1; i++)
                {
                    ListViewItem item = lvControl.Items[i];
                    if (strTenMoi == item.Text)
                    {
                        count += 1;
                        strTenMoi = strTenBanDau + " (" + count + ")";
                        break; 
                    }
                }
                if (i == lvControl.Items.Count)
                {
                    isStop = true;
                }
            }
            return strTenMoi;
        }

        private void ThêmĐơnvịToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string nhomCha = "";
            nhomCha = tvControl.SelectedNode.Name;
            if (nhomCha.Length == CDONVICollection.ColumnLength(nhomColumnName))
            {
                MessageBox.Show("Không thể thêm nhóm được nữa.");
                return; 
            }

            CDONVI cls = new CDONVI();
            cls.NHOM = CDONVICollection.TaoNhom(nhomCha);
            cls.TEN_DONVI = TaoTenCoQuanMoi();
            cls.CUOI = true;
            CDONVICollection.Insert(cls);
            LoadListView(nhomCha);
            lvControl.LabelEdit = true;
            lvControl.Items[cls.NHOM].BeginEdit();
        }

        private void ThêmNhómToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string nhomCha = "";
            nhomCha = tvControl.SelectedNode.Name;
            if (nhomCha.Length == CDONVICollection.ColumnLength(nhomColumnName))
            {
                MessageBox.Show("Không thể thêm nhóm được nữa.");
                return;
            }

            CDONVI cls = new CDONVI();
            cls.NHOM = CDONVICollection.TaoNhom(nhomCha);
            cls.TEN_DONVI = TaoTenNhomMoi();
            cls.CUOI = false;
            CDONVICollection.Insert(cls);
            LoadTreeView(nhomCha);
            LoadListView(nhomCha);
            lvControl.LabelEdit = true;
            lvControl.Items[cls.NHOM].BeginEdit();
        }

        private void QuayLạiToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            if (tvControl.SelectedNode.Parent != null)
            {
                tvControl.SelectedNode = tvControl.SelectedNode.Parent;
                LoadListView(tvControl.SelectedNode.Name);
            }
        }

        private void XóaToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            CDONVI cls = CDONVICollection.LayCoQuanTheoNhom(lvControl.SelectedItems[0].Name);
            string strMsg;
            if (CDONVICollection.IsExistsChildNodes(cls.NHOM, true))
            {
                strMsg = "Nhóm này đang chứa " + name + ", không xóa được.";
                MessageBox.Show(strMsg);
            }
            else if (CDONVICollection.IsExistsInNHANVIEN(cls.ID_DONVI))
            {
                strMsg = "Đang có nhân viên dùng " + name + ", không xóa được.";
                MessageBox.Show(strMsg);
            }
            else
            {
                CDONVICollection.DeleteByNhom(cls.NHOM, true);
                lvControl.SelectedItems[0].Remove();
                LoadTreeView(tvControl.SelectedNode.Name);
            }
        }

        private void CậpNhậtToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            CDONVI cls = CDONVICollection.LayCoQuanTheoNhom(lvControl.SelectedItems[0].Name);
            lvControl.LabelEdit = true;
            lvControl.SelectedItems[0].BeginEdit();
        }

        private void TìmkiếmToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            frmTimKiem frm = new frmTimKiem(this);
            frm.ShowDialog();
        }

        private void TìmKiếmTreeViewToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            if (tvControl.SelectedNode == null)
            {
                frmTimKiem frm = new frmTimKiem(this);
                frm.ShowDialog();
            }
        }

        private void ChọnĐơnvịToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (fCallForm.Name == "frmNHANSU")
            {
                frmNHANSU frm = (frmNHANSU)fCallForm;
                frm.objDonVi = CDONVICollection.LayCoQuanTheoNhom(lvControl.SelectedItems[0].Name);
            }
            this.Close();
        }

        #endregion

        #region "Buttons"

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void thêmNhómToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ThêmNhómToolStripMenuItem_Click(null, null);
        }

        private void thêmĐơnVịToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ThêmĐơnvịToolStripMenuItem_Click(null, null);
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            CậpNhậtToolStripMenuItem_Click(null, null);
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            XóaToolStripMenuItem_Click(null, null);
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            ChọnĐơnvịToolStripMenuItem_Click(null, null);
        }
        #endregion

        private void btnThemMoi_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                //contextMenuStrip3.Items["thêmNhómToolStripMenuItem1"].Visible = true;
                //contextMenuStrip3.Items["thêmĐơnVịToolStripMenuItem1"].Visible = true;

                // Convert from Tree coordinates to Screen coordinates
                Point ScreenPoint = btnThemMoi.PointToScreen(ClickPoint);
                // Convert from Screen coordinates to Formc coordinates
                Point FormPoint = this.PointToClient(ScreenPoint);
                //Show context menu
                contextMenuStrip3.Show(this, FormPoint);
            }
        }

        
    }
}